/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hcsc.datapower.CMDB.service;

import com.hcsc.datapower.CMDB.common.CMDBException;
import com.hcsc.datapower.CMDB.dao.UserDao;
import com.hcsc.datapower.CMDB.integration.User;
import com.hcsc.datapower.CMDB.common.AuthUser;
import com.hcsc.datapower.CMDB.gui.MainApplicationWindow;
import com.hcsc.datapower.CMDB.gui.MainLoginWindow;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author I307211
 */
public class AuthenticationController  {
     
     private UserDao userDao;
     private MainLoginWindow mainloginwindow;
     private MainApplicationWindow mainapplicationwindow;
     
     public AuthenticationController(){}
     
     public void authenticateUser(String username, char[] password) throws CMDBException{
         
        if( (username == null || username.equalsIgnoreCase("") ) || (password == null || password.length==0) ){
            throw new CMDBException(2);
        }

        if(authenticate(username, password)==null){
            //display error, back to login page.
             throw new CMDBException(3);
             //display error, back to login page.
         }else{
                //load 
                getMainapplicationwindow().setVisible(true);
                getMainloginwindow().dispose();
         }
     }
     
     
    public User authenticate(String username, char[] password){
        User tmp = userDao.getUser(username);
        if(tmp!=null && checkPassword(tmp.getPassword(),password) ){
            AuthUser.setCurrentUser(tmp);
            return tmp;
        }
        //if use exists, set currentUser to User, return User bean
        System.out.println("[Username : " + username + " ] [ Password: " + password.toString() +" ] ");
        return null;
    }
    
    private static boolean checkPassword(String db, char[] in){
        char[] input, correct;
        input = in;
        correct = db.toCharArray();
        
        if (Arrays.equals(input, correct))
            return true;

        Arrays.fill(input, ' ');
        return false;
    }

    public UserDao getUserDao() {
        return userDao;
    }

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public MainLoginWindow getMainloginwindow() {
        return mainloginwindow;
    }
    @Autowired
    public void setMainloginwindow(MainLoginWindow mainloginwindow) {
        this.mainloginwindow = mainloginwindow;
    }

    public MainApplicationWindow getMainapplicationwindow() {
        return mainapplicationwindow;
    }
    @Autowired
    public void setMainapplicationwindow(MainApplicationWindow mainapplicationwindow) {
        this.mainapplicationwindow = mainapplicationwindow;
    }
}
